<template>
    <div>
        <!--查询数据-->
        <div>
            <el-form :model="searchForm" :inline="true" v-show="searchShow" label-width="68px">
                <el-form-item label="开始时间">
                    <el-date-picker v-model="searchForm.startTime" type="datetime" placeholder=""
                        :default-time="defaultTime" />
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker v-model="searchForm.endTime" type="datetime" placeholder=""
                        :default-time="defaultTime" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 按钮区域-- -------------------- -->
        <div class="button-container">
            <div>
                <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:user:remove']">删除</el-button>
            </div>
            <div>
                <el-tooltip effect="dark" :content="searchShow ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-button circle :icon="Search" @click="toggleSearch" />
                </el-tooltip>
                <el-tooltip effect="dark" content="刷新" placement="top">
                    <el-button circle :icon="Refresh" @click="refresh" />
                </el-tooltip>
            </div>
        </div>

        <!-- 表格区域-------------------  -----------------------      -->
        <div>
            <el-table :data="tableList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="日志编号" align="center" prop="id" />
                <el-table-column label="操作人员" align="center" prop="operName" />
                <el-table-column label="请求URL" align="center" prop="requestUri" />
                <el-table-column label="请求方式" align="center" prop="requestType" />
                <el-table-column label="请求IP" align="center" prop="requestIp" />
                <el-table-column label="请求地点" align="center" prop="operLocation" />
                <el-table-column label="日志类别" align="center" prop="logType" />
                <el-table-column label="创建时间" align="center" width="160" prop="createDate"
                    :formatter="formatDate"></el-table-column>
                <el-table-column label="操作状态" align="center" prop="status">
                    <template #default="scope">
                        <el-tag type="primary" disable-transitions v-if="scope.row.operStatus === 0">
                            正常
                        </el-tag>
                        <el-tag type="danger" disable-transitions v-if="scope.row.operStatus === 1">
                            异常
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button type="primary" :icon="View" text @click="handleDetail(scope.row, scope.index)">详细</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 ------------------------------------- -->
        <div style="margin-top: 20px">
            <el-pagination v-model:current-page="searchForm.currentPage" v-model:page-size="searchForm.pageSize"
                :page-sizes="[10, 20, 50, 100]" background layout="->, jumper, total, sizes, prev, pager, next"
                :total="PageDataTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 操作日志详细---------------------------------------------------- -->
        <el-dialog title="操作日志详细" v-model="dialogFormVisible" width="800px" append-to-body>
            <el-form :model="form" label-width="100px">
               <el-row>
                <el-col :span="12">
                    <el-form-item label="请求地址：">{{ form.requestUri }}</el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="请求方式：">{{ form.requestType }}</el-form-item>
                </el-col>
               </el-row>
               <el-row>
                    <el-col :span="12">
                        <el-form-item label="请求系统：">{{ form.deviceName }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="请求浏览器：">{{ form.browserName }}</el-form-item>
                    </el-col>
               </el-row>
               <el-row>
                    <el-col :span="8"> <el-form-item label="操作状态：">
                     <div v-if="form.operStatus == 0">正常</div>
                     <div v-else-if="form.operStatus == 1">异常</div>
                  </el-form-item></el-col>
                    <el-col :span="8"><el-form-item label="消耗时间：">{{ form.executeTime }}毫秒</el-form-item></el-col>
                    <el-col :span="8"><el-form-item label="操作时间：">{{ parseTime(form.startTime) }}</el-form-item></el-col>
                 
               </el-row>
               <el-row>
                  <el-form-item label="请求参数：">{{ form.requestParams }}</el-form-item>
               </el-row>
               <el-row>
                  <el-form-item label="返回参数：" width="500px"><div style="word-break: break-all; white-space: pre-wrap;">{{ form.responseResult }}</div></el-form-item>
               </el-row>
               <el-row>
                  <el-form-item label="异常信息：" v-if="form.operStatus === 1">{{ form.exceptionInfo }}</el-form-item>
               </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="onDialogFormCancel">关 闭</el-button>
            </div>
         </template>
        </el-dialog>


    </div>
</template>

<script setup lang="ts">
import { Search, Refresh, View, Delete,  } from '@element-plus/icons-vue'
import { ref } from 'vue'
import {pageListService, deleteLogByIds, detailService} from '@/api/sys/syslog'
import { ElMessage, ElMessageBox } from "element-plus"

// 日期格式化
const formatDate = (row, column) => {
    const date = new Date(row[column.property]);
    return formatDateString(date);
}

const parseTime = (dataString  ) => {
    const date = new Date(dataString);
    return formatDateString(date);
}

const formatDateString = (date) => {
    const year = date.getFullYear();
    const month = pad2(date.getMonth() + 1);
    const day = pad2(date.getDate());
    const hours = pad2(date.getHours());
    const minutes = pad2(date.getMinutes());
    const seconds = pad2(date.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const pad2 = (number) => {
    return (number < 10 ? '0' : '') + number;
};
// 查询区域   -----------------------------------------------------
// 查询参数
const searchForm = ref({
    username: '',
    mobile: '',
    status: '',
    currentPage: 1,
    pageSize: 10,
})
// 是否显示
const searchShow = ref(true)
// 重置查询表单
const resetSearch = () => {
    let currentPage = searchForm.value.currentPage
    let pageSize = searchShow.value.pageSize
    searchForm.value = {}
    searchForm.value.currentPage = currentPage
    searchForm.value.pageSize = pageSize
    getPageList()
}
// 查询事件
const handleSearch = () => {
    getPageList()
}

// 操作按钮区域----------------------------------------------------------------
// 操作区显示隐藏控制
const toggleSearch = () => {
    // console.log("toggleSearch--------------search.valeue", searchShow.value)
    if (searchShow.value) {
        searchShow.value = false
        return
    }
    searchShow.value = true
}
// 刷新
const refresh = () => {
    getPageList()
}
/** 删除按钮操作 */
const handleDelete = () => {
    const Ids = ids.value;
    ElMessageBox.confirm('确认要删除吗？', '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 删除
        console.log("ids = ", Ids)
        let result = await deleteLogByIds(Ids)
        
        if (result.code == 0) {
            ElMessage.success(result.msg ? result.msg : '删除成功')
            getPageList()
        } else {
            ElMessage.error(result.msg ? result.msg : '删除失败')
        }
    })
        .catch(() => { })
}
const handleImport = () => {

}
const handleExport = () => {

}

// 分页----------------------------------------------------------
// 分页数据总条数
const PageDataTotal = ref(0)
// 分页插件，每页条数发生改变时
const handleSizeChange = (val) => {
    searchForm.value.pageSize = val
    getPageList()
}
// 分页插件， 当页码发生改变时
const handleCurrentChange = (val) => {
    searchForm.value.currentPage = val
    getPageList()
}

// 分页查询
const getPageList = async () => {
    // console.log("getPageList:", searchForm.value);
    let param = JSON.parse(JSON.stringify(searchForm.value))
    if (searchForm.value.status === undefined || searchForm.value.status === '') {
        param.status = -1;
    }
    try {
        const result = await pageListService(param)
        PageDataTotal.value = result.data.total;
        tableList.value = result.data.list;
    } catch (err) { }
    //console.log("tableData:", tableData);
}
getPageList()


// 表格区域----------------------------------------------------------------
// 表格数据
const tableList = ref()
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
/** 选择条数  */
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id);
    console.log("ids.value:", ids.value);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

const handleDetail = async (row, index) => {
    try {
        let result = await detailService(row.id)
        form.value = result.data
        dialogFormVisible.value = true
    } catch (e) {}

}


/** 详情表单----------------------------------------- */
const dialogFormVisible = ref(false)
const form = ref()

// 取消对话表单框按钮事件
const onDialogFormCancel = () => {
    dialogFormVisible.value = false
}




</script>